//
//  TimeAlertView.m
//  Growkin
//
//  Created by haohao on 2017/1/17.
//  Copyright © 2017年 万浩. All rights reserved.
//

#import "TimeAlertView.h"
#import "PeopleCenterToolkit.h"
@interface TimeAlertView ()<UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, strong) UIPickerView *datePickView;

@property (nonatomic, strong) UIView *pickerView;

@property (nonatomic, strong) UIView *alert;

@property (nonatomic, strong) NSMutableArray *yearArray;

@property (nonatomic, strong) NSArray *dayArray;

@property (nonatomic, strong) NSArray *monthArray;

@end

@implementation TimeAlertView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        self.frame = CGRectMake(0, 0, KWidthSCREEN, KHeightSCREEN);

        [self setupWithBlackView];
        [self setupWithSupViews];

    }
    return self;
}
//设置弹出的动画
- (void)setupWithBlackView {
    UIView *blackView = [[UIView alloc] init];
    //    blackView.layer.cornerRadius = 10;
    blackView.layer.masksToBounds = YES;
    self.alert = blackView;
    blackView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:255 / 255.0 blue:255 / 255.0 alpha:1];
    [self addSubview:blackView];
}


- (void)setupWithSupViews {
    self.alert = [[UIView alloc] initWithFrame:CGRectMake(0, KHeightSCREEN - 220, KWidthSCREEN, 220 )];
    self.alert.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.alert];
    
    UIButton *cencelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    cencelButton.frame = CGRectMake(20 , 14, 50 , 30);
    [cencelButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [cencelButton setTintColor:[UIColor blackColor]];
    cencelButton.layer.cornerRadius = 4;
    cencelButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
    cencelButton.tag = 106;
    [cencelButton setTitleColor:kMainColor forState:UIControlStateNormal];
    [cencelButton setTitle:@"取消" forState:UIControlStateNormal];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(cencelButton.frame) + 10, 14, KWidthSCREEN - 20 * 2 - 50 * 2 - 10 * 2, 30)];
    titleLabel.textColor = kMainColor;
    titleLabel.text = @"请选择时间";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:18.0];
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(CGRectGetMaxX(titleLabel.frame) + 10, 14, 50, 30 );
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 4;
    button.tag = 105;
    [button setTitleColor:kMainColor forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [button setTitle:@"确认" forState:UIControlStateNormal];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(button.frame) + 5, KWidthSCREEN, 1)];
    lineLabel.backgroundColor = k999999;
    
    _datePickView = [[UIPickerView alloc] initWithFrame:CGRectMake(10 , 50 , KWidthSCREEN, 150)];
    _datePickView.delegate = self;
    _datePickView.dataSource = self;
    [self setDefaultTime];
    
    [self.alert addSubview:_datePickView];
    [self.alert addSubview:button];
    [self.alert addSubview:cencelButton];
    [self.alert addSubview:lineLabel];
    [self.alert addSubview:titleLabel];
}

- (void)buttonClick:(UIButton *)button {
    NSInteger yearRow = [self.datePickView selectedRowInComponent:0];
    _year = self.yearArray[yearRow];
    NSInteger monthRow = [self.datePickView selectedRowInComponent:2];
    _month = self.monthArray[monthRow];
    
    NSInteger day = [self.datePickView selectedRowInComponent:4];
    _dateString = [NSString stringWithFormat:@"%@-%02ld-%02ld", _year, [_month integerValue], day + 1];
    
    if([self.delegate respondsToSelector:@selector(pickerView:clickedButtonWithDate:)]) {
        [self.delegate pickerView:self clickedButtonWithDate:_dateString];
    }
    [self dismiss];
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 6;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.yearArray.count;
    } else if (component == 1) {
        return 1;
    }else if (component == 2){
        return self.monthArray.count;
    } else if (component == 3) {
        return 1;
    } else if (component == 4){
        if (self.monthArray != 0 && self.yearArray.count != 0) {
            NSInteger yearRow = [self.datePickView selectedRowInComponent:0];
            _year = self.yearArray[yearRow];
            NSInteger monthRow = [self.datePickView selectedRowInComponent:2];
            _month = self.monthArray[monthRow];
            
            return [[self getDayNumber:[_year integerValue]  month:[_month integerValue]] integerValue];
        } else {
            return 0;
        }

    } else {
        return 1;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return self.yearArray[row];
    } else if (component == 1) {
        return @"年";
    }else if (component == 2){
        return self.monthArray[row];
    } else if (component == 3) {
        return @"月";
    } else if (component == 4){
        return [NSString stringWithFormat:@"%ld", row + 1];
    } else {
        return @"日";
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
   
    UILabel* pickerLabel = (UILabel*)view;
    
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        
        if (component == 0 || component == 2 || component == 4) {
            pickerLabel.textColor=kMainColor;
            [pickerLabel setFont:[UIFont boldSystemFontOfSize:24]];
        }
        if (component == 1 || component == 3 || component == 5) {
            pickerLabel.textColor  = [UIColor blackColor];
            [pickerLabel setFont:[UIFont boldSystemFontOfSize:18]];
        }
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
    
}

#pragma mark - UIPickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component != 4) {
        [_datePickView reloadComponent:4];
    }
}



- (void)show {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    self.alpha = 0;
    self.alert.transform = CGAffineTransformMakeScale(1.08, 1.08);
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 1;
        self.alert.transform = CGAffineTransformIdentity;
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:0.38 animations:^{
        self.alpha = 0;
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (NSMutableArray *)yearArray {
    if (_yearArray == nil) {
        _yearArray = [NSMutableArray array];
        // 获取代表公历的NSCalendar对象
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        // 获取当前日期
        NSDate* dt = [NSDate date];
        // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
        unsigned unitFlags = NSCalendarUnitYear |
        NSCalendarUnitMonth |  NSCalendarUnitDay |
        NSCalendarUnitHour |  NSCalendarUnitMinute |
        NSCalendarUnitSecond | NSCalendarUnitWeekday;
        // 获取不同时间字段的信息
        NSDateComponents* comp = [gregorian components: unitFlags 
                                              fromDate:dt];
        NSLog(@"%ld", (long)comp.year);
        _nowYear = [NSString stringWithFormat:@"%ld", (long)comp.year];
        for (int i = 2015; i < comp.year + 100; i++) {
            [_yearArray addObject:[NSString stringWithFormat:@"%d", i]];
        }
    }
    return _yearArray;
}

- (NSArray *)monthArray {
    if (_monthArray == nil) {
        _monthArray = @[@"1", @"2", @"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12"];
    }
    return _monthArray;
}

- (NSString *)getDayNumber:(NSInteger)year month:(NSInteger)month{
    NSArray *days = @[@"31", @"28", @"31", @"30", @"31", @"30", @"31", @"31", @"30", @"31", @"30", @"31"];
    if (2 == month && 0 == (year % 4) && (0 != (year % 100) || 0 == (year % 400))) {
        return @"29";
    }
    return days[month - 1];
}

- (void)setDefaultTime {
    NSDate *now = [NSDate date];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
    NSInteger year = [dateComponent year];
    NSInteger month =  [dateComponent month];
    NSInteger day = [dateComponent day];
    
    [_datePickView selectRow:year - 2015 inComponent:0 animated:NO];
    [_datePickView selectRow:month - 1 inComponent:2 animated:NO];
    [_datePickView selectRow:day - 1 inComponent:4 animated:NO];


}

@end
